
package GUILayer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

import ControlLayer.CustomerCtr;
import ControlLayer.OrderCtr;
import ModelLayer.*;


public class OrderMenu extends javax.swing.JFrame {
	private static OrderMenu instance;
	
	private static final long serialVersionUID = 1L;
    private OrderMenu() {
       
        initComponents();
        setVisible(true);
    }
    
	public static OrderMenu getInstance()
	{
		if(instance==null)
		{
			instance = new OrderMenu();
		}
		return instance;		
	}    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jLabel7 = new javax.swing.JLabel();
        txtDeliveryDate = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        inCustomerName = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jButton5 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Order information");

        jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 18));
        jLabel1.setText("Order information");

        jLabel2.setText("Order ID");

        jLabel3.setText("Order date");

        jLabel4.setText("Delivery status");

        jTextField1.setName("txtOrderId"); // NOI18N

        jTextField2.setName("txtLname"); // NOI18N

        jTextField3.setName("txtSsn"); // NOI18N

        jButton2.setText("Search");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchOrder(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Products"));

        jLabel5.setText("Product");

        jLabel6.setText("Quantity");

        jScrollPane1.setViewportView(jList1);
        
        JLabel lblNewLabel = new JLabel("Price");
        
        JButton btnAddProducts = new JButton("Add Products");
        btnAddProducts.addActionListener(new ActionListener() {
        	public void actionPerformed(ActionEvent e) {
        		ProductLineMenu productLine = ProductLineMenu.getInstance();
        		productLine.frame.setVisible(true);
        	}
        });
        
        JButton btnRemoveProduct = new JButton("Remove Product");

        GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
        jPanel1Layout.setHorizontalGroup(
        	jPanel1Layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(jPanel1Layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(jPanel1Layout.createParallelGroup(Alignment.LEADING)
        				.addGroup(jPanel1Layout.createSequentialGroup()
        					.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 257, GroupLayout.PREFERRED_SIZE)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addGroup(jPanel1Layout.createParallelGroup(Alignment.LEADING)
        						.addComponent(btnRemoveProduct, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        						.addComponent(btnAddProducts, GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)))
        				.addGroup(jPanel1Layout.createSequentialGroup()
        					.addComponent(jLabel5, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE)
        					.addGap(35)
        					.addComponent(jLabel6, GroupLayout.PREFERRED_SIZE, 57, GroupLayout.PREFERRED_SIZE)
        					.addGap(26)
        					.addComponent(lblNewLabel)))
        			.addGap(32))
        );
        jPanel1Layout.setVerticalGroup(
        	jPanel1Layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(jPanel1Layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(jPanel1Layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabel5)
        				.addComponent(lblNewLabel)
        				.addComponent(jLabel6))
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addGroup(jPanel1Layout.createParallelGroup(Alignment.BASELINE, false)
        				.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 92, GroupLayout.PREFERRED_SIZE)
        				.addGroup(jPanel1Layout.createSequentialGroup()
        					.addComponent(btnAddProducts)
        					.addGap(12)
        					.addComponent(btnRemoveProduct, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)))
        			.addGap(51))
        );
        jPanel1.setLayout(jPanel1Layout);

        jLabel7.setText("Delivery date");

        txtDeliveryDate.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        jLabel8.setText("Customer");

        inCustomerName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inCustomerNameActionPerformed(evt);
            }
        });

        jButton1.setText("Show Products");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                findProductInformation(evt);
            }
        });

        jButton3.setText("Clear");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearFields(evt);
            }
        });

        jButton4.setText("Update");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateSalesOrder(evt);
            }
        });

        jButton5.setText("Insert");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insertOrder(evt);
            }
        });

        jLabel10.setText("Invoice No");
        
        JLabel lblOrderPrice = new JLabel("Order price:");
        
        txtOrderprice = new JTextField();
        txtOrderprice.setColumns(10);

        GroupLayout layout = new GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addGroup(layout.createSequentialGroup()
        					.addContainerGap()
        					.addGroup(layout.createParallelGroup(Alignment.LEADING, false)
        						.addGroup(layout.createParallelGroup(Alignment.TRAILING)
        							.addComponent(jPanel1, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        							.addGroup(layout.createSequentialGroup()
        								.addGroup(layout.createParallelGroup(Alignment.TRAILING)
        									.addGroup(layout.createSequentialGroup()
        										.addComponent(jLabel3, GroupLayout.PREFERRED_SIZE, 82, GroupLayout.PREFERRED_SIZE)
        										.addGap(14)
        										.addGroup(layout.createParallelGroup(Alignment.LEADING)
        											.addGroup(layout.createSequentialGroup()
        												.addComponent(jTextField3, GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)
        												.addPreferredGap(ComponentPlacement.RELATED)
        												.addComponent(jLabel9, GroupLayout.PREFERRED_SIZE, 219, GroupLayout.PREFERRED_SIZE))
        											.addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
        												.addComponent(jTextField2, Alignment.LEADING)
        												.addComponent(jTextField1, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE))))
        									.addComponent(jLabel2, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 107, GroupLayout.PREFERRED_SIZE))
        								.addGap(37)
        								.addGroup(layout.createParallelGroup(Alignment.LEADING)
        									.addComponent(jLabel10, GroupLayout.PREFERRED_SIZE, 87, GroupLayout.PREFERRED_SIZE)
        									.addComponent(jLabel7, GroupLayout.PREFERRED_SIZE, 105, GroupLayout.PREFERRED_SIZE)
        									.addComponent(jLabel8))))
        						.addComponent(jLabel4)
        						.addGroup(layout.createSequentialGroup()
        							.addComponent(jButton2, GroupLayout.PREFERRED_SIZE, 147, GroupLayout.PREFERRED_SIZE)
        							.addGap(32)
        							.addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 123, GroupLayout.PREFERRED_SIZE)
        							.addGap(33)
        							.addComponent(jButton3, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE)
        							.addGap(34)
        							.addGroup(layout.createParallelGroup(Alignment.LEADING)
        								.addGroup(layout.createSequentialGroup()
        									.addComponent(lblOrderPrice)
        									.addPreferredGap(ComponentPlacement.RELATED)
        									.addComponent(txtOrderprice, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        								.addComponent(jButton4, GroupLayout.PREFERRED_SIZE, 119, GroupLayout.PREFERRED_SIZE))))
        					.addPreferredGap(ComponentPlacement.RELATED, 6, Short.MAX_VALUE)
        					.addGroup(layout.createParallelGroup(Alignment.LEADING, false)
        						.addComponent(inCustomerName, GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
        						.addComponent(txtDeliveryDate, GroupLayout.PREFERRED_SIZE, 73, GroupLayout.PREFERRED_SIZE)
        						.addComponent(jTextField6)
        						.addComponent(jButton5, GroupLayout.PREFERRED_SIZE, 81, GroupLayout.PREFERRED_SIZE)))
        				.addGroup(layout.createSequentialGroup()
        					.addGap(199)
        					.addComponent(jLabel1, GroupLayout.PREFERRED_SIZE, 242, GroupLayout.PREFERRED_SIZE)))
        			.addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.LEADING)
        		.addGroup(layout.createSequentialGroup()
        			.addGap(23)
        			.addComponent(jLabel1)
        			.addGap(37)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabel2)
        				.addComponent(jLabel7)
        				.addComponent(txtDeliveryDate, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jTextField1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addGroup(layout.createSequentialGroup()
        					.addGap(19)
        					.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        						.addComponent(jLabel3)
        						.addComponent(jTextField2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        					.addGroup(layout.createParallelGroup(Alignment.LEADING)
        						.addGroup(layout.createSequentialGroup()
        							.addPreferredGap(ComponentPlacement.RELATED)
        							.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        								.addComponent(jLabel9)
        								.addComponent(jLabel10)
        								.addComponent(jTextField6, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        								.addComponent(jTextField3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
        						.addGroup(layout.createSequentialGroup()
        							.addGap(15)
        							.addComponent(jLabel4)))
        					.addGap(27)
        					.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        						.addComponent(jButton2, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE)
        						.addComponent(jButton1, GroupLayout.PREFERRED_SIZE, 28, GroupLayout.PREFERRED_SIZE)
        						.addComponent(jButton3)
        						.addComponent(jButton4)
        						.addComponent(jButton5)))
        				.addGroup(layout.createSequentialGroup()
        					.addGap(14)
        					.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        						.addComponent(jLabel8)
        						.addComponent(inCustomerName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addGroup(layout.createSequentialGroup()
        					.addGap(27)
        					.addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        				.addGroup(layout.createSequentialGroup()
        					.addGap(66)
        					.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        						.addComponent(lblOrderPrice)
        						.addComponent(txtOrderprice, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
        			.addContainerGap(27, Short.MAX_VALUE))
        );
        getContentPane().setLayout(layout);

        pack();
    }

    private void insertOrder(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertEmp
        OrderCtr orderCtr = new OrderCtr();
  
        String orderDate = jTextField2.getText();
        String deliveryStatus = jTextField3.getText();
        String deliveryDate = txtDeliveryDate.getText();
        String customerName = inCustomerName.getText();
        int invoiceNo = Integer.parseInt(jTextField6.getText());
        Customer customer = checkCustomer(customerName);
        if(customer != null){
        	orderCtr.createNewOrder(orderDate, deliveryStatus, deliveryDate, customer.getID(), invoiceNo);
        }
        else{
            jLabel9.setText("Customer is not in the system");
        }
    }

    private void findProductInformation(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findProjectInformation
          OrderCtr orderCtr = new OrderCtr();
          String orderId = jTextField1.getText();
          if (orderId.length() == 0){
              jLabel9.setText("Please insert order ID");
          }
          else {
              ArrayList<ProductLine> orderProducts = orderCtr.findAllProductLinesForOrder(Integer.parseInt(orderId));
              buildList(orderProducts);
          }
    }

    private void updateSalesOrder(java.awt.event.ActionEvent evt) {  
           //read the new values from the screen and update them in the database
           OrderCtr orderCtr = new OrderCtr();
           int orderId = Integer.parseInt(jTextField1.getText()); 
           String orderDate = jTextField2.getText();
           String deliveryStatus = jTextField3.getText();
           String deliveryDate = txtDeliveryDate.getText();
           String customerName = inCustomerName.getText();
           int invoiceNo = Integer.parseInt(jTextField6.getText());
           Customer customer = checkCustomer(customerName);
           Invoice invoice = orderCtr.findInvoiceByNo(invoiceNo);
           if(customer != null && invoice != null){               
               int result = orderCtr.updateSalesOrder(orderId, orderDate, deliveryStatus, deliveryDate, customer.getID(), invoice.getInvoiceNo());
               if(result == 1){
                clearFields();}
               else{
                  jLabel9.setText("Problem with update");
               }
           }
           else
           {
                  jLabel9.setText("The supervisor is not correct ");
           }              
    }
    
    private Customer checkCustomer(String name){
        CustomerCtr customerCtr = new CustomerCtr();
        return customerCtr.getCustomerByName(name);
    }
    
    private void clearFields(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearFields
         clearFields();        
    }

    private void searchOrder(java.awt.event.ActionEvent evt) 
    {     
       OrderCtr orderCtr = new OrderCtr();
       String input = jTextField1.getText();
       System.out.println(input);
       
       //search by ID
       SalesOrder order = orderCtr.findOrderById(Integer.parseInt(input));
       if(String.valueOf(order.getId()).equals(""))
       {
    	   jLabel9.setText("The inserted order ID does not exists");
       }
       else
       {
    	   clearFields();
           putValuesOnTheScreen(order);
       }
    }                              
 
    private void inCustomerNameActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
    
    private void clearFields()
    {
          jTextField1.setText("");
          jTextField2.setText("");
          jTextField3.setText("");
          txtDeliveryDate.setText("");
          inCustomerName.setText("");
          jTextField6.setText("");
          txtOrderprice.setText("");
          jLabel9.setText("");
          String[] empty = new String[5];
          jList1.setListData(empty);
    }
    
    private void putValuesOnTheScreen(SalesOrder order)
    {
    	OrderCtr orderCtr = new OrderCtr();
    	
          jTextField1.setText(String.valueOf(order.getId()));
          jTextField2.setText(order.getOrderDate());
          jTextField3.setText(order.getDeliveryStatus());
          txtDeliveryDate.setText(order.getDeliveryDate());
          inCustomerName.setText(String.valueOf(order.getCustomer().getID()));
          jTextField6.setText(String.valueOf(order.getInvoice().getInvoiceNo()));     
          txtOrderprice.setText(String.valueOf(orderCtr.findOrderPrice(order.getId())));
    }
    
    private void buildList(ArrayList<ProductLine> orderProduct)
    {   
        String[] productLines = new String[orderProduct.size()];
        int index = 0;
        for(ProductLine pl : orderProduct)
        {
        
            String productName = pl.getProduct().getName();
            if(productName.length() < 15){
                int length = productName.length();
                while (length < 20)
               {
                  productName = productName + "  ";
                  length++;
               }
            }
            productLines[index] =(productName + "  " + pl.getQuantity()+"                      "+pl.getSubPrice());
            index++;
        }
        jList1.setListData(productLines);
    }
    
 
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OrderMenu();
                
            }
        });
    }
    
    // Variables declaration
    private javax.swing.JTextField txtDeliveryDate;
    private javax.swing.JTextField inCustomerName;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField6;
    private JTextField txtOrderprice;
}
